package com.mssh.login.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mssh.entity.pojo.Result;
import com.mssh.login.config.AuthConfig;
import com.mssh.login.dto.LoginDto;
import com.mssh.login.mapper.SysUserMapper;
import com.mssh.login.service.AuthService;
import com.mssh.login.util.JwtUtil;
import com.mssh.login.util.SecurityUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;


/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 熳殊沙华
 * @Date: 2025/03/26/9:35
 * @Description:
 */
@Service
public class AuthServiceImpl implements AuthService {

    private final static Logger logger = LogManager.getLogger(AuthServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DefaultKaptcha kaptcha;

    /**
     * 登录
     * @return
     */
    @Override
    public Result login(LoginDto dto) {
        Result result = new Result();
        try {
            if(dto == null || StringUtils.isBlank(dto.getAccount()) || StringUtils.isBlank(dto.getPassword())){
                logger.warn("登录失败，登录请求参数为空！");
                return result.failed("登录失败，登录请求参数为空！");
            }
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(dto.getAccount(), dto.getPassword());
            //获取subject
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            if (subject.isAuthenticated()) { // 确保认证成功
                //验证成功后返回token给客户端
                String salt = SecurityUtil.generateSalt();
                String token = JwtUtil.generateToken(dto.getAccount(), salt);
                //redis缓存token
                String redisKey = "token:user:" + dto.getAccount();
                redisTemplate.opsForValue().set(redisKey, token, 60, TimeUnit.MINUTES);
                JSONObject resp = new JSONObject();
                resp.put("token", token);
                resp.put("account", dto.getAccount());
                result.success(resp, "登录成功！");
            }else{
                result.failed("登录失败！");
            }
        } catch (UnknownAccountException e) {
            //账号错误
            logger.warn("账号[{}]错误", dto.getAccount());
            result.failed("未查询到用户信息！");
        } catch (IncorrectCredentialsException e) {
            //密码错误
            logger.warn("账号[{}]密码错误", dto.getAccount());
            result.failed("密码错误！");
        } catch (Exception e) {
            logger.warn("账号[{}]登录异常:{}", dto.getAccount(), e);
            result.failed("登录异常！");
        }
        return result;
    }

    /**
     * 生成验证码图片
     * @param request
     * @param response
     * @throws Exception
     */
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 生成验证码文本和图片
        String text = kaptcha.createText();
        BufferedImage image = kaptcha.createImage(text);

        // 将验证码存入Redis（有效期5分钟）
        String key = "captcha:" + request.getSession().getId();
        redisTemplate.opsForValue().set(key, text, AuthConfig.getVerifyCodeExpire(), TimeUnit.MINUTES);

        // 返回图片流
        response.setContentType("image/jpeg");
        try (OutputStream out = response.getOutputStream()) {
            ImageIO.write(image, "jpg", out);
        }
    }
}
